﻿import threading
import time
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
import os

# ============================================================
# 服务器逻辑（等价于 startServer）
# ============================================================
def start_server():
    class Handler(BaseHTTPRequestHandler):

        def do_GET(self):
            if self.path == "/":
                json_path = os.path.join("src", "八_汉字模型.json")

                # 读取 JSON 文件内容
                with open(json_path, "r", encoding="utf-8") as f:
                    data = f.read()

                # 发送响应头
                self.send_response(200)
                self.send_header("Content-Type", "application/json; charset=utf-8")
                self.end_headers()

                # 写出 body
                self.wfile.write(data.encode("utf-8"))
            else:
                self.send_response(404)
                self.end_headers()

    # 创建 server
    server = HTTPServer(("127.0.0.1", 8080), Handler)
    print("服务器已启动: http://127.0.0.1:8080")
    server.serve_forever()


# ============================================================
# 客户端逻辑（等价于 startClient）
# ============================================================
def start_client():
    response = requests.get("http://127.0.0.1:8080/")
    print("客户端收到 JSON：")
    print(response.text)


# ============================================================
# main：后台线程启动 server → sleep → 启动 client
# ============================================================
def main():
    # 启动服务器线程
    server_thread = threading.Thread(target=start_server, daemon=True)
    server_thread.start()

    # 等待服务器启动
    time.sleep(1)

    # 启动客户端
    start_client()


if __name__ == "__main__":
    main()
